const express = require("express");
const router = express.Router();
const FormData = require("form-data");
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const process = require("process");

router.get("/", function (req, res) {
  res.redirect("/static/index.html");
});

router.get("/scenes", function (req, res) {
  const dirPath = `${process.cwd()}/public/images/scenes`;
  const scenes = fs.readdirSync(dirPath);
  const rtnObjs = scenes.map((item) => {
    return {
      name: item,
      path: path.join("images", "scenes", item),
    };
  });

  return res.json(rtnObjs);
});

router.post("/run-next", async (req, res) => {
  try {
    const formData = new FormData();
    formData.append("traj", req.body.traj);
    // formData.append("angle", req.body.angle);
    formData.append("scene", req.body.scene);
    const url = `http://${req.body.targetIp}:${req.body.targetPort}/api/run`;
    await axios.post(url, formData, formData.getHeaders());
    return res.json({ code: 0 });
  } catch (err) {
    console.log(`出现异常：${err}`);
    return res.json({ code: 1, message: "下位机激活失败" });
  }
});

module.exports = router;
